from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

from apps.articles.serializers import ArticleModelSerializer
from apps.chat.serializers import SystemMessageModelSerializer
from apps.users.models import ChatMessage

channel_layer = get_channel_layer()


class Notification:
    def __init__(self, event, from_user, to_user, target_article=None):
        self.event = event
        self.from_user = from_user
        self.to_user = to_user
        self.target_article = target_article

    def send_system_message(self):
        global channel_layer
        message = f'{self.from_user.username}{self.event}了你'
        if self.event == '评论' or self.event == '收藏':
            message += '的文章:  ' + self.target_article.title
        if self.event == '点赞':
            if self.target_article:
                message += '的评论:  ' + self.target_article.content
        try:
            count = ChatMessage.objects.filter(sender=self.from_user, message=message, receiver=self.to_user).count()
            if count > 0:
                return
            message_obj = ChatMessage.objects.get_or_create(sender=self.from_user, receiver=self.to_user,
                                                            message=message, is_system=True)
            serializer = SystemMessageModelSerializer(message_obj)
        except Exception as e:
            print(e)
            return
        async_to_sync(channel_layer.send)(self.to_user.chat_client.channel_name,
                                          {'type': 'system.message', 'message': serializer.data})
